package cn.iocoder.yudao.module.tms.service.training;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.tms.controller.admin.training.vo.*;
import cn.iocoder.yudao.module.tms.dal.dataobject.training.TrainingMaterialDO;
import cn.iocoder.yudao.module.tms.dal.mysql.training.TrainingMaterialMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.tms.enums.ErrorCodeConstants.TRAINING_MATERIAL_NOT_EXISTS;

/**
 * 培训资料 Service 实现类
 */
@Service
@Validated
public class TrainingMaterialServiceImpl implements TrainingMaterialService {

    @Resource
    private TrainingMaterialMapper trainingMaterialMapper;

    @Override
    public Long createTrainingMaterial(TrainingMaterialSaveReqVO createReqVO) {
        // 插入
        TrainingMaterialDO trainingMaterial = BeanUtils.toBean(createReqVO, TrainingMaterialDO.class);
        trainingMaterial.setCreateTime(LocalDateTime.now());
        trainingMaterial.setUpdateTime(LocalDateTime.now());
        trainingMaterialMapper.insert(trainingMaterial);
        // 返回
        return trainingMaterial.getId();
    }

    @Override
    public void updateTrainingMaterial(TrainingMaterialSaveReqVO updateReqVO) {
        // 校验存在
        validateTrainingMaterialExists(updateReqVO.getId());
        // 更新
        TrainingMaterialDO updateObj = BeanUtils.toBean(updateReqVO, TrainingMaterialDO.class);
        updateObj.setUpdateTime(LocalDateTime.now());
        trainingMaterialMapper.updateById(updateObj);
    }

    @Override
    public void deleteTrainingMaterial(Long id) {
        // 校验存在
        validateTrainingMaterialExists(id);
        // 删除
        trainingMaterialMapper.deleteById(id);
    }

    private void validateTrainingMaterialExists(Long id) {
        if (trainingMaterialMapper.selectById(id) == null) {
            throw exception(TRAINING_MATERIAL_NOT_EXISTS);
        }
    }

    @Override
    public TrainingMaterialRespVO getTrainingMaterial(Long id) {
        TrainingMaterialDO trainingMaterial = trainingMaterialMapper.selectById(id);
        return BeanUtils.toBean(trainingMaterial, TrainingMaterialRespVO.class);
    }

    @Override
    public PageResult<TrainingMaterialRespVO> getTrainingMaterialPage(TrainingMaterialPageReqVO pageReqVO) {
        return BeanUtils.toBean(trainingMaterialMapper.selectPage(pageReqVO), TrainingMaterialRespVO.class);
    }

}